package com.qmx.launcher.activity.base;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.qmx.launcher.QMXApplication;
import com.qmx.launcher.R;
import com.qmx.launcher.activity.MyTimeActivity;
import com.qmx.launcher.bean.ConfigInfo;
import com.qmx.launcher.bean.LzyResponse;
import com.qmx.launcher.bean.MessageObservable;
import com.qmx.launcher.bean.TokenListModel;
import com.qmx.launcher.callback.JsonCallback;
import com.qmx.launcher.constant.AppConstant;
import com.qmx.launcher.constant.ComParamContact;
import com.qmx.launcher.realm.TokenList;
import com.qmx.launcher.token.TokenManager;
import com.qmx.launcher.utils.NetCheckUtils;
import com.tencent.ilivesdk.ILiveSDK;
import com.tencent.ilivesdk.adapter.CommonConstants;
import com.tencent.ilivesdk.core.ILiveLoginManager;
import com.tencent.ilivesdk.core.ILiveRoomConfig;
import com.tencent.ilivesdk.core.ILiveRoomManager;
import com.tencent.ilivesdk.listener.ILiveEventHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import io.realm.Realm;

import static com.qmx.launcher.constant.AppConstant.NET;


/**
 * @author ChengXiangtong
 * @create 2018/10/8
 * @Describe
 */
public class BaseActivity extends AppCompatActivity {
    private TextView current_text_title;
    private TextView terminal_number;
    private TextView terminal_state;
    private ImageView img_link, img_wifi;
    protected final String TAG = this.getClass().getSimpleName();
    public SharedPreferences sharedPreferences;
    public SharedPreferences.Editor editor;
    private Gson mGson = new Gson();
    private Realm realm;
    public String __TOKEN__ = "";
    private List<TokenList> lists;
    public NetCheckUtils mNetCheckUtils;
    private LinearLayout rootLayout;
    public CountDownTimer countDownTimer;
    private long advertisingTime = 15000 * 1000;//定时跳转广告时间
    public Context context;
    private Intent intent;
    private int REQ_PERMISSION_CODE = 13;

    //网络监听图片数组
    public static int[] mNetLogo = new int[]{R.drawable.wifi0, R.drawable.wifi1,
            R.drawable.wifi2, R.drawable.wifi3, R.drawable.icon_link,
            R.drawable.etnerror, R.drawable.wifinotnormal};

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case NET:
                    int obj = (int) msg.obj;
                    //                    Log.e("handleMessage", "obj==" + obj);
                    if (obj == 4 || obj == 5) {//有线图标
                        img_link.setImageResource(mNetLogo[obj]);
                    } else {
                        img_wifi.setImageResource(mNetLogo[obj]);
                    }
                    break;
            }
        }
    };


    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //有按下动作时取消定时
                if (countDownTimer != null) {
                    countDownTimer.cancel();
                }
                break;
            case MotionEvent.ACTION_UP:
                //抬起时启动定时
                Log.i("dispatchTouchEvent", "抬起时启动定时");
                startAD();
                break;
        }
        return super.dispatchKeyEvent(event);
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                //有按下动作时取消定时
                if (countDownTimer != null) {
                    countDownTimer.cancel();
                }
                break;
            case MotionEvent.ACTION_UP:
                //抬起时启动定时
                Log.i("dispatchTouchEvent", "抬起时启动定时");
                startAD();
                break;
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 跳转到广告
     */
    public void startAD() {
        if (countDownTimer == null) {
            countDownTimer = new CountDownTimer(advertisingTime, 1000l) {
                @Override
                public void onTick(long millisUntilFinished) {

                }

                @Override
                public void onFinish() {
                    //定时完成后的操作
                    //跳转到广告页面
                    if (intent == null) {
                        intent = new Intent(context, MyTimeActivity.class);
                    }
                    Log.i("startAD", "跳转到广告页面");
                    startActivity(intent);
                }
            };
            countDownTimer.start();
        } else {
            countDownTimer.start();
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        //显示是启动定时
        startAD();
    }

    @Override
    protected void onPause() {
        super.onPause();
        //当activity不在前台是停止定时
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁时停止定时
        if (intent != null) {
            Log.i("onDestroy", "销毁时停止定时");
            stopService(intent);
        }
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
    }

    protected void setTitle(String msg) {
        if (current_text_title != null) {
            current_text_title.setText(msg);
        }
    }

    protected void setTerminalNumber(String msg) {
        if (terminal_number != null) {
            terminal_number.setText(msg);
        }
    }


    public float getDimension(int id) {
        return getResources().getDimension(id);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // 经测试在代码里直接声明透明状态栏更有效
        //        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
        //            getWindow().setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
        //                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        //        }
        //        getWindow().addPrivateFlags(WindowManager.LayoutParams.PRIVATE_FLAG_HOMEKEY_DISPATCHED);

        //        Log.e("基本信息", "----" + SystemInfoUtils.getUserAgent(QMXApplication.getInstance(), "123456"));
        // 这句很关键，注意是调用父类的方法
        super.setContentView(R.layout.activity_base);
        sharedPreferences = getSharedPreferences(QMXApplication.getInstance().getPackageName(), Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        context = this;
        initToolbar();
    }

    //开启新线程，防止阻塞UI主线程
    public void checkNet() {
        Thread mThread = new Thread(new Runnable() {
            @Override
            public void run() {
                Log.e("handleCheckNet", "checkNet");
                mNetCheckUtils = new NetCheckUtils(BaseActivity.this, mHandler);//网络
                mNetCheckUtils.getNetwork();
            }
        });
        mThread.start();

    }

    private void initToolbar() {
        img_link = (ImageView) findViewById(R.id.img_link);
        img_wifi = (ImageView) findViewById(R.id.img_wifi);
        terminal_number = (TextView) findViewById(R.id.terminal_number);
        terminal_state = (TextView) findViewById(R.id.terminal_state);
        current_text_title = (TextView) findViewById(R.id.current_text_title);
    }


    @Override
    public void setContentView(int layoutId) {
        setContentView(View.inflate(this, layoutId, null));
    }

    @Override
    public void setContentView(View view) {
        rootLayout = (LinearLayout) findViewById(R.id.root_layout);
        if (rootLayout == null)
            return;
        rootLayout.addView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        rootLayout.setBackgroundColor(R.drawable.text_bg_gradient);
        initToolbar();

        sharedPreferences = getSharedPreferences(QMXApplication.getInstance().getPackageName(), Context.MODE_PRIVATE);
        editor = sharedPreferences.edit();
    }


    public void token(Realm mRealm) {
        mRealm.executeTransaction(new Realm.Transaction() {
            @Override
            public void execute(Realm realm) {
                TokenList list = realm.where(TokenList.class).findFirst();
                if (list != null) {
                    __TOKEN__ = list.getToken();
                    list.deleteFromRealm();
                }
                Log.i("BaseActivity", __TOKEN__ + "--------" + (mRealm.where(TokenList.class).findAll()).size());
            }
        });
    }

    public void getHttpToken() {
        realm = Realm.getDefaultInstance();
        lists = realm.where(TokenList.class).findAll();
        if (!lists.isEmpty() && lists.size() != 0) {
            realm.executeTransactionAsync(new Realm.Transaction() {
                @Override
                public void execute(Realm realm) {
                    realm.deleteAll();
                }
            });
        }
        OkGo.<LzyResponse<TokenListModel>>post(AppConstant.Url + ComParamContact.tokenFrom.PATH)
                .headers(ComParamContact.tokenFrom.TOKEN, TokenManager.getInstance().getAuthModel().getToken())
                .execute(new JsonCallback<LzyResponse<TokenListModel>>() {
                    @Override
                    public void onSuccess(Response<LzyResponse<TokenListModel>> response) {
                        String json = mGson.toJson(response.body().data);
                        final TokenListModel contactModel = mGson.fromJson(json, TokenListModel.class);
                        Log.i("getHttpToken===", contactModel.get__token__() + "");

                        realm.executeTransactionAsync(new Realm.Transaction() {
                            @Override
                            public void execute(Realm realm) {
                                for (String s : contactModel.get__token__()) {
                                    TokenList tokenList = realm.createObject(TokenList.class);
                                    tokenList.setToken(s);
                                }
                            }
                        });
                        lists = realm.where(TokenList.class).findAll();
                        Log.i("getHttpToken", lists.size() + "");

                    }

                    @Override
                    public void onError(Response<LzyResponse<TokenListModel>> response) {
                        Log.e("getHttpToken ", response.toString());
                        //                            handleError(response);
                    }
                });

    }

    public void saveClientId(JSONObject jsonObject) {
        Log.i("saveClientId", "" + jsonObject);
        try {
            if (!jsonObject.opt("code").equals(911)) {
                String str = new JSONObject(jsonObject.opt("data").toString()).opt("client_id").toString();
                Log.i("CLIENT_ID===", str);
                editor.putString(AppConstant.CLIENT_ID, str);
                editor.commit();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }


    /**
     * 初始化并登录TRTC SDK
     */
    public void afterUserSelected(String userId) {
        // Step 1: 初始化TRTC SDK
        initTrtcSDK(ConfigInfo.getInstance().getSdkAppId());
        // Step 2: 登录TRTC SDK
        loginTrtcSDK(userId, sharedPreferences.getString(AppConstant.USER_SIG, ""));
        Log.e("afterUserSelected", userId + "------------" + sharedPreferences.getString(AppConstant.USER_SIG, ""));
    }

    /**
     * 初始化TRTC SDK
     */
    private void initTrtcSDK(int sdkAppId) {
        // 初始化ILiveSDK
        ILiveSDK.getInstance().initSdk(BaseActivity.this, sdkAppId, 0);
        // 初始化房间模块
        ILiveRoomManager.getInstance().init(new ILiveRoomConfig()
                .setRoomMsgListener(MessageObservable.getInstance()));
        ILiveSDK.getInstance().setChannelMode(CommonConstants.E_ChannelMode.E_ChannelIMSDK);
        //        Log.e("ILiveSDK ", ILiveSDK.getInstance().getVersion());
        //        Log.e("AVSDK  ", AVContext.sdkVersion);
        //        Log.e("IMSDK  ", TIMManager.getInstance().getVersion());
        ILiveSDK.getInstance().setChannelMode(CommonConstants.E_ChannelMode.E_ChannelIMSDK);
    }

    /**
     * 登录TRTC SDK
     */
    private void loginTrtcSDK(String useId, String userSig) {
        // 添加事件监听
        ILiveSDK.getInstance().addEventHandler(new ILiveEventHandler() {
            // 登录成功事件
            @Override
            public void onLoginSuccess(String userId) {
                //                bLogin = true;
                Log.e("onLoginSuccess", "登录成功: " + userId);
                //                DlgMgr.showToast(BaseActivity.this, getString(R.string.str_login_success));
            }

            // 登录失败事件
            @Override
            public void onLoginFailed(String userId, String module, int errCode, String errMsg) {
                //                DlgMgr.showMsg(BaseActivity.this, "登录失败: " + module + "|" + errCode + "|" + errMsg);
                Log.e("onLoginFailed", "登录失败: " + module + "|" + errCode + "|" + errMsg);
            }

            // 帐号被踢
            @Override
            public void onForceOffline(String userId, String module, int errCode, String errMsg) {
                //                bLogin = false;
                Log.e("onForceOffline", "登录失败: " + module + "|" + errCode + "|" + errMsg);
                //                DlgMgr.showMsg(BaseActivity.this, "帐号被踢下线: " + module + "|" + errCode + "|" + errMsg);
            }
        });
        Log.e("onLoginSuccess", "登录成功: " + useId + "userSig==" + userSig);
        // 登录SDK
        ILiveLoginManager.getInstance().iLiveLogin(useId, userSig, null);
    }

    public void showToast(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }

    /**
     * 读取配置文件
     */
    public void loadConfigData() {
        try {
            ConfigInfo.getInstance().loadConfig(this, R.raw.config);
        } catch (Exception e) {
            Log.e("loadConfigData", "读取配置文件失败，请在【控制台】->【快速上手】中生成配置内容复制到config.json文件");
        }
    }

    /**
     * 动态权限申请
     */
    public boolean checkPermission() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            List<String> permissions = new ArrayList<>();

            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.CHANGE_NETWORK_STATE)) {
                permissions.add(Manifest.permission.CHANGE_NETWORK_STATE);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)) {
                permissions.add(Manifest.permission.CAMERA);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO)) {
                permissions.add(Manifest.permission.RECORD_AUDIO);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE)) {
                permissions.add(Manifest.permission.READ_PHONE_STATE);
            }
            if (PackageManager.PERMISSION_GRANTED != ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                permissions.add(Manifest.permission.READ_EXTERNAL_STORAGE);
            }
            if (permissions.size() != 0) {
                ActivityCompat.requestPermissions(this, permissions.toArray(new String[0]), REQ_PERMISSION_CODE);
                return false;
            }
        }

        return true;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            //            case REQ_PERMISSION_CODE:
            //                for (int ret : grantResults) {
            //                    if (PackageManager.PERMISSION_GRANTED != ret) {
            //                        //                        DlgMgr.showMsg(this, "用户没有允许需要的权限，使用可能会受到限制！");
            //                        Log.e("estPermissionsResult", "用户没有允许需要的权限，使用可能会受到限制！");
            //                    }
            //                }
            //                break;
            default:
                break;
        }
    }

}
